package edu.gatech.geochat;

import edu.gatech.geochat.database.Storage;
import edu.gatech.geochat.model.GeoMessage;
import edu.gatech.geochat.model.User;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class AddNoteActivity extends BetterActivity {
	
	public static void launch(Activity source, User user) {
		if (user == null) return;
		Intent intent = new Intent(source, AddNoteActivity.class);
		source.startActivity(intent);
		
		GUISpace.put(AddNoteActivity.class, "user", user);
	}
	
	private EditText noteText;
	private CheckBox displayEmail, displaySignature;
	
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.add_note);
		noteText= (EditText)this.findViewById(R.id.writeNoteField);
		displaySignature=(CheckBox)this.findViewById(R.id.showNameBox);
		displayEmail=(CheckBox)this.findViewById(R.id.showEmailBox);
		
	}
	
	private volatile boolean trying = false;
	private synchronized void tryAddNote() {
		if (trying) return;
		trying = true;
		setStatusText("Waiting for GPS location...");
		
		final Activity me = this;
		new Thread() { public void run() {

			User user=(User) GUISpace.get(AddNoteActivity.class, "user");
			String range="15";//will later be selected by spinner
			String text=noteText.getEditableText().toString();
			String email="";
			String username=user.getUsername();
			String anon = "1";
			if(displaySignature.isChecked()){
				anon = "0";
			}
			if(displayEmail.isChecked()){
				email=user.getEmail();
			}
			
			
//			Log.d("AddNoteActivity", "getLocation()");
//			LocationCode.getLocation(me);
//			Log.d("AddNoteActivity", "getLatitude()");
//			String lat = LocationCode.getLatitude(me);
//			Log.d("AddNoteActivity", "getLongitude()");
//			String lon = LocationCode.getLongitude(me);
			
			String lat = "0";
			String lon = "0";
			
			GeoMessage message=new GeoMessage(
											username,
											user.getPassword(),
											email,
											text,
											lat+","+lon, 
											range);
			message.setAnon(anon);

			setStatusText("Sending data to server...");
			String response = Storage.getInstance().addMessage(user, message);
			setStatusText(response);
			
			if (response == Storage.RESPONSE_SUCCESS) {			
				finish();
			}
			
			trying = false;
		}}.start();
	}
	
	public void addNote(View view){
		if (trying) return;
		
		tryAddNote();
	}
	
	public void cancelAddNote(View view){
		this.finish();
	}

}
